package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.RecommendUserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserServiceImpl implements RecommendUserService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 根据当前登录用户id 查询推荐用户
     * @param loginUserId
     * @return
     */
    @Override
    public RecommendUser findRecommendUserByUserId(Long loginUserId) {
        Query query = new Query(
                Criteria.where("toUserId").is(loginUserId) // 查询给谁推送的用户
        ).with(Sort.by(Sort.Order.desc("score")))//按照缘分值进行排序
                .skip(0).limit(1);//只查询一条数据

        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }


    /**
     * 根据当前登录用户id 查询多个推荐用户
     * @param pageNumber
     * @param pageSize
     * @param loginUserId
     * @return
     */
    @Override
    public PageBeanVo findRecommendUser(Integer pageNumber, Integer pageSize, Long loginUserId) {

        int startIndex = (pageNumber - 1 ) * pageSize  + 1 ;

        Query query = new Query(
                Criteria.where("toUserId").is(loginUserId) // 查询给谁推送的用户
        ).with(Sort.by(Sort.Order.desc("score")))//按照缘分值进行排序
                .skip(startIndex).limit(pageSize);//只查询一条数据

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        long counts = mongoTemplate.count(query, RecommendUser.class);

        return new PageBeanVo(pageNumber , pageSize , counts ,recommendUserList);
    }

    /**
     * 根据当前登录用户id 和 推荐用户id   查询推荐的用户信息
     * @param loginUserId
     * @param recommendUserId
     * @return
     */
    @Override
    public RecommendUser findRecommendUser(Long loginUserId, Long recommendUserId) {

        Query query = new Query(
                Criteria.where("userId").is(recommendUserId)
                .and("toUserId").is(loginUserId)
        );
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }
}
